package com.aiboleepro.base;

import com.aiboleepro.constant.ErrorCode;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 * 生成jwt
 *
 * @author aiboleepro
 * @date 2018-08-30 上午12:09
 **/
public class BaseJwtWorker<ClientId extends String, Extension extends BaseObject> {

    private final String CLIENT_ID = "clientId";
    private final String EXTENSION = "extension";

    public BaseAuthToken create(String signKey,
                                long expiresIn,
                                ClientId clientId,
                                Extension extension) {
        BaseAuthToken baseAuthToken = new BaseAuthToken();
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        baseAuthToken.setAccessExpiresIn(expiresIn);
        baseAuthToken.setRefreshExpiresIn(expiresIn * 2);
        Date accessExp = new Date(nowMillis + expiresIn);
        Date refreshExp = new Date(nowMillis + expiresIn * 2);

        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("type", "jwt")
                .claim(CLIENT_ID, clientId)
                .claim(EXTENSION, JSONObject.toJSONString(extension))
                .signWith(signatureAlgorithm, signKey);
        builder.setExpiration(accessExp).setNotBefore(now);

        baseAuthToken.setAccessToken(builder.compact());
        builder = Jwts.builder()
                .setHeaderParam("type", "jwt")
                .claim(CLIENT_ID, clientId)
                .claim(EXTENSION, JSONObject.toJSONString(extension))
                .signWith(signatureAlgorithm, signKey);

        builder.setExpiration(refreshExp).setNotBefore(now);
        baseAuthToken.setRefreshToken(builder.compact());
        return baseAuthToken;
    }

    public String getClientId(String token, String signKey) {
        try {
            Claims body = Jwts.parser().setSigningKey(signKey).parseClaimsJws(token).getBody();
            return body.get(CLIENT_ID, String.class);
        }catch (Exception e){
            throw new BaseException(ErrorCode.TOKEN_ERROR, "TOKEN失效");
        }
    }

    public Extension getExtension(String token, String signKey, Class<Extension> extensionClass) {
        try {
            Claims body = Jwts.parser().setSigningKey(signKey).parseClaimsJws(token).getBody();
            return JSONObject.parseObject(body.get(EXTENSION, String.class), extensionClass);
        }catch (Exception e){
            throw new BaseException(ErrorCode.TOKEN_ERROR, "TOKEN失效");
        }
    }

}
